package cn.yx.common.security.webmvc.access;

import cn.yx.permission.remote.dto.RolePermissionRemoteDto;
import cn.yx.permission.remote.service.RolePermissionRemoteService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>用户资源与角色元数据，获取能够访问某个资源（拥有某个权限）的角色</p>
 *
 * @author Wgssmart
 */
@Component
public class CustomInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @DubboReference(check = false)
    private RolePermissionRemoteService rolePermissionRemoteService;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        List<RolePermissionRemoteDto> rolePermissionRemoteDtoList = rolePermissionRemoteService.listAll();
        List<ConfigAttribute> configAttributes = new ArrayList<>();
        FilterInvocation filterInvocation = (FilterInvocation) o;
        for (RolePermissionRemoteDto rolePermissionRemoteDto : rolePermissionRemoteDtoList) {
            AntPathRequestMatcher matcher = new AntPathRequestMatcher(rolePermissionRemoteDto.getPermission());
            if (matcher.matches(filterInvocation.getRequest())) {
                // 如果某个角色拥有资源，则添加到configAttributes中
                configAttributes.add(new SecurityConfig(rolePermissionRemoteDto.getRole()));
            }
        }
        return configAttributes;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

}
